using System;
using System.Collections.Generic;
using System.Threading;

namespace BanZuiCloudControlAgent.Core.Tasks.Models
{
    /// <summary>
    /// 任务上下文，提供任务执行过程中需要的上下文信息和服务
    /// </summary>
    public class TaskContext
    {
        /// <summary>
        /// 取消令牌
        /// </summary>
        public CancellationToken CancellationToken { get; set; }
        
        /// <summary>
        /// 上下文数据
        /// </summary>
        public Dictionary<string, object> Data { get; set; }
        
        /// <summary>
        /// 任务创建时间
        /// </summary>
        public DateTime CreatedTime { get; set; }
        
        /// <summary>
        /// 任务开始执行时间
        /// </summary>
        public DateTime StartTime { get; set; }
        
        /// <summary>
        /// 设备码
        /// </summary>
        public string DeviceCode { get; set; }
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public TaskContext()
        {
            Data = new Dictionary<string, object>();
            CreatedTime = DateTime.Now;
            StartTime = DateTime.Now;
        }
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="deviceCode">设备码</param>
        /// <param name="cancellationToken">取消令牌</param>
        public TaskContext(string deviceCode, CancellationToken cancellationToken = default)
        {
            DeviceCode = deviceCode;
            CancellationToken = cancellationToken;
            Data = new Dictionary<string, object>();
            CreatedTime = DateTime.Now;
            StartTime = DateTime.Now;
        }
        
        /// <summary>
        /// 获取上下文数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="key">键</param>
        /// <returns>数据值</returns>
        public T GetData<T>(string key)
        {
            if (Data.TryGetValue(key, out object value) && value is T typedValue)
            {
                return typedValue;
            }
            
            return default;
        }
        
        /// <summary>
        /// 设置上下文数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public void SetData(string key, object value)
        {
            if (Data.ContainsKey(key))
            {
                Data[key] = value;
            }
            else
            {
                Data.Add(key, value);
            }
        }
        
        /// <summary>
        /// 检查是否已取消
        /// </summary>
        /// <returns>是否已取消</returns>
        public bool IsCancellationRequested()
        {
            return CancellationToken.IsCancellationRequested;
        }
        
        /// <summary>
        /// 检查取消令牌并抛出异常
        /// </summary>
        public void ThrowIfCancellationRequested()
        {
            CancellationToken.ThrowIfCancellationRequested();
        }
    }
} 